﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;
using YXY.Identity.ApiResult;
using YXY.Identity.Service.HttpContextUser;

namespace YXY.Identity.Service.Filter
{
    /// <summary>
    /// 验证超级管理员角色过滤器
    /// </summary>
    public class ValidateAdminActionFilter : IAsyncActionFilter
    {
        /// <summary>
        /// 获取用户信息
        /// </summary>
        protected readonly IHttpContextUser _httpContextUser;
        /// <summary>
        /// 构造函数
        /// </summary>
        public ValidateAdminActionFilter(IHttpContextUser httpContextUser)
        {
            _httpContextUser = httpContextUser;
        }
        /// <summary>
        /// 执行器
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //执行前验证当前登录用户角色是否正确
            if (!ValidateHttpUserRole(1))
            {
                context.HttpContext.Response.ContentType = "application/json";

                CommonResult commonResult = new CommonResult()
                {
                    Code = -100,
                    Msg = $"请使用超级管理员角色调用接口",
                    Success = false
                };

                await context.HttpContext.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(commonResult)).ConfigureAwait(false);
            }
            else
            {
                await next();
            }


        }
        /// <summary>
        /// 验证 用户角色是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateHttpUserRole(int userRole)
        {
            var userInfo = _httpContextUser.GetUserInfo();

            if (userInfo == null)
                return false;

            if (userInfo.RoleId != userRole)
                return false;
            return true;
        }
    }
}
